import ChatManager from '../component/ChatManager';
import JsBridge from './JsBridge';

class Api {
  constructor() {}

  imageUrl(path) {
    let index = path.indexOf('Upload');
    if (index > 0) {
      path = path.slice(index - 1);
    }
    return API.baseUrl + '/' + path;
  }

  get(url, data) {
    return $.get(API.baseUrl + url, data).then((resp) => {
      // console.log(`${url}: ${JSON.stringify(resp)}`)
      // console.log(`data: ${JSON.stringify(data)}`)
      if (resp && resp.Goodo && resp.Goodo.EID) {
        if (resp.Goodo.EID === "0") {
          return resp;
        } else if (resp.Goodo.EID === "1") {
          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
            const fistLog = JSON.parse(jsrep.data.value);
            const user = fistLog.logs[0].user;
            const pass = fistLog.logs[0].pass;
            const UnitUrl = fistLog.logs[0].UnitUrl;
            const UnitUrl2 = fistLog.logs[0].UnitUrl2;
//          console.log(user)
//          console.log(pass)
//          console.log(5555555555555555555)
//          //				alert('有掉线')
//          console.log(UnitUrl)
//
									JsBridge.sendRequest("user.password", {password: pass}).then(resp => {
						      $.ajax({
						        url: API.baseUrl + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
						        type: "post",
						        dataType: "json",
						        data: {
						          LoginID: user,
						          EncyptPassword: resp.data.password,
						          OnlineType: 130,
						          DeviceName: 'web test',
						          Place: 'cs'
						        },
						        success: function (json) {

						          layer.closeAll();
//						          alert(111);
						          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
//						              alert(JSON.stringify(jsrep));
						              let cookie_log = jsrep.data.value;
						              let logs = [];
						              if (cookie_log) {
						                logs = JSON.parse(cookie_log).logs;
						              }

						              if (json.Goodo.UserName) {
						                $(".login").unbind("click");
						                //Cookies.set("yxtUser", json.Goodo);

						                JsBridge.sendRequest('user.login', { userInfo: json.Goodo, LoginID: user, EncyptPassword: resp.data.password, UnitUrl: API.baseUrl,UnitUrl2: UnitUrl2 , UnitName: json.Goodo.UnitName });

						                localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));
						                // 找出同单位同姓名的记录并删除
						                let { Unit_ID, UnitName, UserName, User_ID } = json.Goodo;
						                let repeatIndex;
						                for (let i = 0; i < logs.length; i++) {
						                  if (logs[i].Unit_ID === Unit_ID && logs[i].User_ID === User_ID) {
						                    repeatIndex = i;
						                    break;
						                  }
						                }
						                repeatIndex >= 0 && logs.splice(repeatIndex, 1); // 去重
						                logs.unshift({ Unit_ID, UnitName, UserName, User_ID, UnitUrl: API.baseUrl,UnitUrl2, user, pass }); // 添加新记录
						                JsBridge.sendRequest("custom.set", {key: 'yxtLog', value: JSON.stringify({ "logs": logs })}) // 添加到本地

//						                location.href = `index.html?burl=${url}`; // 跳转到首页
														ChatManager.refreshUser();

						              } else {
//						              	alert('重登录出错')
						                layer.msg(`${json.Goodo.ErrorMessage}`);

						              }
						          	});


						        },
						        error: function (err) {
						          layer.closeAll();
						          layer.msg('网络请求超时出错');
						          // console.log(err);
						        }
						      });

            //              layer.msg('未登录', {
            //                time: 2000
            //              }, function(){
            //                window.location.href = 'fist_login.html';
            //              });
          })
        })

        } else {
          return resp;
        }
      } else {
        return resp;
      }
    });
  }

  post(url, data ) {
    return $.post(API.baseUrl + url, data).then((resp) => {
      if (resp && resp.Goodo && resp.Goodo.EID) {
        if (resp.Goodo.EID === "0") {
          return resp;
        } else if (resp.Goodo.EID === "1") {
          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
            const fistLog = JSON.parse(jsrep.data.value);
            const user = fistLog.logs[0].user;
            const pass = fistLog.logs[0].pass;
            const UnitUrl = fistLog.logs[0].UnitUrl;
             const UnitUrl2 = fistLog.logs[0].UnitUrl2;
//          console.log(user)
//          console.log(pass)
//          console.log(5555555555555555555)
//          //				alert('有掉线')
//          console.log(UnitUrl)
//
                  JsBridge.sendRequest("user.password", {password: pass}).then(resp => {
                  $.ajax({
                    url: API.baseUrl + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
                    type: "post",
                    dataType: "json",
                    data: {
                      LoginID: user,
                      EncyptPassword: resp.data.password,
                      OnlineType: 130,
                      DeviceName: 'web test',
                      Place: 'cs'
                    },
                    success: function (json) {

                      layer.closeAll();
//						          alert(111);
                      JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
//						              alert(JSON.stringify(jsrep));
                          let cookie_log = jsrep.data.value;
                          let logs = [];
                          if (cookie_log) {
                            logs = JSON.parse(cookie_log).logs;
                          }

                          if (json.Goodo.UserName) {
                            $(".login").unbind("click");
                            //Cookies.set("yxtUser", json.Goodo);
 																console.log(json)
 																console.log('看url2')
                            JsBridge.sendRequest('user.login', { userInfo: json.Goodo, LoginID: user, EncyptPassword: resp.data.password, UnitUrl: API.baseUrl,UnitUrl2: UnitUrl2 , UnitName: json.Goodo.UnitName });

                            localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));
                            // 找出同单位同姓名的记录并删除
                            let { Unit_ID, UnitName, UserName, User_ID } = json.Goodo;
                            let repeatIndex;
                            for (let i = 0; i < logs.length; i++) {
                              if (logs[i].Unit_ID === Unit_ID && logs[i].User_ID === User_ID) {
                                repeatIndex = i;
                                break;
                              }
                            }
                            repeatIndex >= 0 && logs.splice(repeatIndex, 1); // 去重
                            logs.unshift({ Unit_ID, UnitName, UserName, User_ID, UnitUrl: API.baseUrl,UnitUrl2:UnitUrl2, user, pass }); // 添加新记录
                            JsBridge.sendRequest("custom.set", {key: 'yxtLog', value: JSON.stringify({ "logs": logs })}) // 添加到本地

//						                location.href = `index.html?burl=${url}`; // 跳转到首页
                            ChatManager.refreshUser();

                          } else {
//						              	alert('重登录出错')
                            layer.msg(`${json.Goodo.ErrorMessage}`);

                          }
                        });


                    },
                    error: function (err) {
                      layer.closeAll();
                      layer.msg('网络请求超时出错');
                      // console.log(err);
                    }
                  });

            //              layer.msg('未登录', {
            //                time: 2000
            //              }, function(){
            //                window.location.href = 'fist_login.html';
            //              });
          })
        })

        } else {
          return resp;
        }
      } else {
        return resp;
      }
    });
  }

  get2(url, data) {
    return $.get(API.RbaseUrl + url, data);
  }

  uploadFile(url, data, progressUCB, progressDCB) {
    return $.ajax({
        xhr: function() {
            var xhr = new window.XMLHttpRequest();

            // Upload progress
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    //Do something with upload progress
                    console.log(percentComplete);
                    progressUCB(percentComplete);
                }
           }, false);

           // Download progress
           xhr.addEventListener("progress", function(evt){
               if (evt.lengthComputable) {
                   var percentComplete = evt.loaded / evt.total;
                   // Do something with download progress
                   console.log(percentComplete);
                   progressDCB(percentComplete);
               }
           }, false);

           return xhr;
        },
        type: 'POST',
        url: API.baseUrl + url,
        data: data
    }).then(resp => {
      if (resp && resp.Goodo && resp.Goodo.EID) {
        if (resp.Goodo.EID === "0") {
          return resp;
        } else if (resp.Goodo.EID === "1") {
          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
            const fistLog = JSON.parse(jsrep.data.value);
            const user = fistLog.logs[0].user;
            const pass = fistLog.logs[0].pass;
            const UnitUrl = fistLog.logs[0].UnitUrl;
            const UnitUrl2 = fistLog.logs[0].UnitUrl2;
//          console.log(user)
//          console.log(pass)
//          console.log(5555555555555555555)
//          //				alert('有掉线')
//          console.log(UnitUrl)
//
                  JsBridge.sendRequest("user.password", {password: pass}).then(resp => {
                  $.ajax({
                    url: API.baseUrl + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
                    type: "post",
                    dataType: "json",
                    data: {
                      LoginID: user,
                      EncyptPassword: resp.data.password,
                      OnlineType: 130,
                      DeviceName: 'web test',
                      Place: 'cs'
                    },
                    success: function (json) {

                      layer.closeAll();
//						          alert(111);
                      JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
//						              alert(JSON.stringify(jsrep));
                          let cookie_log = jsrep.data.value;
                          let logs = [];
                          if (cookie_log) {
                            logs = JSON.parse(cookie_log).logs;
                          }

                          if (json.Goodo.UserName) {
                            $(".login").unbind("click");
                            //Cookies.set("yxtUser", json.Goodo);

                            JsBridge.sendRequest('user.login', { userInfo: json.Goodo, LoginID: user, EncyptPassword: resp.data.password, UnitUrl: API.baseUrl,UnitUrl2: UnitUrl2, UnitName: json.Goodo.UnitName });

                            localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));
                            // 找出同单位同姓名的记录并删除
                            let { Unit_ID, UnitName, UserName, User_ID } = json.Goodo;
                            let repeatIndex;
                            for (let i = 0; i < logs.length; i++) {
                              if (logs[i].Unit_ID === Unit_ID && logs[i].User_ID === User_ID) {
                                repeatIndex = i;
                                break;
                              }
                            }
                            repeatIndex >= 0 && logs.splice(repeatIndex, 1); // 去重
                            logs.unshift({ Unit_ID, UnitName, UserName, User_ID, UnitUrl: API.baseUrl,UnitUrl2: UnitUrl2, user, pass }); // 添加新记录
                            JsBridge.sendRequest("custom.set", {key: 'yxtLog', value: JSON.stringify({ "logs": logs })}) // 添加到本地

//						                location.href = `index.html?burl=${url}`; // 跳转到首页
                            ChatManager.refreshUser();

                          } else {
//						              	alert('重登录出错')
                            layer.msg(`${json.Goodo.ErrorMessage}`);

                          }
                        });


                    },
                    error: function (err) {
                      layer.closeAll();
                      layer.msg('网络请求超时出错');
                      // console.log(err);
                    }
                  });

            //              layer.msg('未登录', {
            //                time: 2000
            //              }, function(){
            //                window.location.href = 'fist_login.html';
            //              });
          })
        })

        } else {
          return resp;
        }
      } else {
        return resp;
      }
    });
  }

}

export default new Api();
